<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ExampleGenerate } from './detail'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/renxuan'
import detailStore from '@/store/modules/NewCacheData'
import { GetOptionData } from '@/api/modules/voucher.ts'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<ExampleGenerate>({
  title: '',
  banner: '',
  amount: 0,
  nums: 0,
  zengpinTitle: '',
  zengpinPic: '',
  zengpinCode: '',
  shareTxt: '',
  shareImg: '',
  actStatus: 0,
  desp: '',
})

const id = route.query.id as string

const options = ref([
  { value: 0, label: '未开始' },
  { value: 1, label: '进行中' },
  { value: 2, label: '已结束' },
])

const rules = reactive({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  banner: [
    { required: true, message: '请上传banner图', trigger: 'blur' },
  ],
  amount: [
    { required: true, message: '请输入价格', trigger: 'blur' },
  ],
  nums: [
    { required: true, message: '请输入件数', trigger: 'blur' },
  ],
  zengpinTitle: [
    { required: true, message: '请输入赠品标题', trigger: 'blur' },
  ],
  zengpinPic: [
    { required: true, message: '请上传赠品图片', trigger: 'blur' },
  ],
  zengpinCode: [
    { required: true, message: '请输入赠品编码', trigger: 'blur' },
  ],
  shareTxt: [
    { required: true, message: '请输入分享语', trigger: 'blur' },
  ],
  shareImg: [
    { required: true, message: '请输入分享图', trigger: 'blur' },
  ],
  actStatus: [
    { required: true, message: '请选择活动状态', trigger: 'blur' },
  ],
  desp: [
    { required: true, message: '请输入描述', trigger: 'blur' },
  ],
})

const OptionList = reactive({
  CouponOption: [],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  ruleForm.value[key] = url
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }

      if (id) {
        // 编辑
        params.rxActId = id

        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'renxuanIndex' })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        // console.log(params)

        PostCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('renxuanFrom')
            router.push({ name: 'renxuanIndex' })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('renxuanFrom')
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('renxuanFrom', newValue)
    }
    ruleForm.value.outProductCode = ruleForm.value.outProductCode.replace(/[^a-z0-9\u4E00-\u9FA5 ]/gi, '')
  }, { deep: true })

  // 获取所有商品
  const CouponOption: any = await GetOptionData()
  if (CouponOption.succeeded) {
    OptionList.CouponOption = CouponOption.data
    nextTick(() => {
      OptionList.CouponOption = CouponOption.data
    })
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="标题" prop="title">
              <el-input v-model="ruleForm.title" placeholder="请输入标题" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动状态" prop="actStatus">
              <el-segmented
                v-model="ruleForm.actStatus"
                :options="options"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="价格" prop="amount">
              <el-input v-model="ruleForm.amount" placeholder="请输入价格" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="任选件数" prop="nums">
              <el-input v-model="ruleForm.nums" placeholder="请输入任选件数" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="赠品标题">
              <el-input v-model="ruleForm.zengpinTitle" placeholder="请输入赠品标题" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="赠品编码">
              <el-input
                v-model.trim="ruleForm.zengpinCode" placeholder="请输入赠品编码"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="分享语" prop="shareTxt">
              <el-input v-model="ruleForm.shareTxt" placeholder="请输入分享语" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="描述" prop="desp">
              <el-input v-model="ruleForm.desp" placeholder="请输入描述" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="banner图" prop="banner">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.banner" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'banner')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="赠品图片">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.zengpinPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'zengpinPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图" prop="shareImg">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.shareImg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'shareImg')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
